<template>
  <div class="shareRegister hideScrollBar" ref="scrollEl">
    <!-- 导航 -->
    <NavBar
      :title="$t('inviteFriends.zcqr')"
      isTransparent
      :navScorllOffset="60"
      navScorllColor="#FFF"
      :scrollEl="scrollEl"
      isCusRightBtns
      isFixed
      :customBackFn="handleBack"
    />
    <div class="shareRegister-bg"></div>
    <!-- 内容部分 -->
    <div class="content">
      <!-- 标题 -->
      <div class="content-title">
        <img class="content-title-leftimg" src="/image/green-icon.svg" />
        <div class="content-title-text">{{ $t("inviteFriends.ndzcxx") }}</div>
        <img class="content-title-rightimg" src="/image/green-icon.svg" />
      </div>
      <!-- 信息 -->
      <div class="content-info">
        <!-- 邮箱 -->
        <div class="content-select items-center">
          <div class="content-select-left">
            {{ $t("common.email") }}
          </div>
          <div class="content-select-right items-center">
            <div class="content-select-code">{{ email }}</div>
          </div>
        </div>
        <!-- 密码 -->
        <van-field
          class="content-registerInput"
          label-class="content-registerInput-label"
          v-model="password"
          type="text"
          input-align="right"
          center
          clearable
          :label="$t('common.password')"
          :placeholder="$t('inviteFriends.qsrmm')"
        />
        <!-- 地区选择 -->
        <div class="content-select items-center">
          <div class="content-select-left">
            {{ $t("inviteFriends.dqText") }}
          </div>
          <div class="content-select-right items-center" @click="showRegio">
            <FlagIcon
              v-if="areaCode"
              class="content-select-icon"
              :iso="areaCode"
            />
            <div class="content-select-code">{{ area }}</div>
            <img class="content-select-btn" src="/image/jt-right-icon.svg" />
          </div>
        </div>
        <!-- 名称 -->
        <van-field
          class="content-registerInput"
          label-class="content-registerInput-label"
          style="margin-bottom: 0"
          v-model="name"
          type="text"
          input-align="right"
          center
          clearable
          :label="$t('common.name')"
          :placeholder="$t('airdrop.qsr')"
        />
      </div>
      <!-- 注册按钮 -->
      <div class="content-btn" @click="clickRegister">
        {{ $t("inviteFriends.ljzc") }}
      </div>
    </div>
    <!-- 选择区域国旗 -->
    <SearchFlag
      v-model:show="isShowSearchFlag"
      @changeCode="changeCode"
    ></SearchFlag>
  </div>
</template>
<script setup name="shareRegister" lang="ts">
import {
  newMailboxRegister,
  validateTripartiteLogin,
  newMailboxRegisterCode,
} from "@/api/user";
import SearchFlag from "~~/components/invite-friends/search-flag.vue";
import { useTripartiteStore } from "~~/store/modules/useTripartiteStore";
import FlagIcon from "~~/components/flag-icon/index.vue";
import { useGlobalStore } from "~~/store/global";
import { nation } from "~/config/nation";
import { isiOS } from "@/utils";

const scrollEl = ref();
const { t } = useI18n();
const route = useRoute();
console.log("页面参数:", route.query);

const globalStore = useGlobalStore();

// firebase埋点
const firebase = useInitFirebase();
const tripartiteState = useTripartiteStore();

// 页面属性
const email = ref("");
const password = ref("");
const name = ref("");
const area = ref(""); // 地区: +62
const areaCode = ref(null); // 区域 code
const chinese = ref(null); // 区域 名称

/***************** 地区展示 *****************/
const isShowSearchFlag = ref(false);

const showRegio = () => {
  isShowSearchFlag.value = true;
};
const changeCode = (val: any) => {
  console.log("选择了地区:", val);
  areaCode.value = val.code;
  area.value = `+${val.dialCode}`;
  chinese.value = val.chinese;
};

onMounted(() => {
  // 1. 埋点
  firebase?.logEvent("BDC_H5_invite-friends-Register_PUV");
  // 2. 赋值参数
  if (route.query) {
    if (route.query.email) {
      email.value = route.query.email;
      // 2.1 如果没有名称,默认是邮箱前缀
      const list = email.value.split("@");
      if (!name.value) name.value = list[0];
    }
    if (route.query.password) {
      password.value = route.query.password;
    }
  }
  // 2. 地区
  console.log("--globalStore.$state--", globalStore.$state);
  if (globalStore.$state.publicArea) {
    area.value = `+${globalStore.$state.publicArea}`;
    const areaInfo = Object.values(nation).find(
      (item) => item.dialCode === globalStore.$state.publicArea
    );
    areaCode.value = areaInfo?.code;
    chinese.value = areaInfo.chinese;
  }
});

// 三方授权注册
const validateTripartiteLoginApi = async (call: any) => {
  const result = await validateTripartiteLogin({
    areaCode: area.value,
    areaName: chinese.value,
    email: email.value,
    inviteId: route.query.inviteCode ?? "", // 邀请ID
    nickname: name.value,
    password: password.value,
    type: tripartiteState.type,
    openID: tripartiteState.openID,
    idToken: tripartiteState.idToken,
    userSource: 11,
    // emailStatus: tripartiteState.email == email.value ? "0" : "1", // 增加以后,接口报错,请联系管理员
  });
  if (result) {
    globalStore.$patch({
      token: result?.user?.token ?? "",
    });
    // 注册成功
    showToast(t("inviteFriends.zccg"));
    call && call(true);
  } else {
    call && call(false);
  }
};
// 邮箱注册
const newMailboxRegisterApi = async (call: any) => {
  // let fn = route.query.emailKey ? newMailboxRegisterCode : newMailboxRegister;
  const result = await newMailboxRegisterCode({
    areaCode: area.value,
    areaName: chinese.value,
    email: email.value,
    inviteId: route.query.inviteCode ?? "", // 邀请ID
    nickname: name.value,
    password: password.value,
    lastLoginIp: globalStore.$state.publicIp ?? "",
    userSource: 11,
    key: route.query.emailKey || "", // newMailboxRegisterCode: 邮箱验证成功的 key
  });

  if (result && result != 1003) {
    globalStore.$patch({
      token: result?.user?.token ?? "",
    });
    // 注册成功
    showToast(t("inviteFriends.zccg"));
    call && call(true);
  } else if (result == 1003) {
    // 提示邮箱已经注册过
    showToast(t("inviteFriends.yxyjzc"));
    call && call(false);
  } else {
    call && call(false);
  }
};

// 点击注册
const clickRegister = () => {
  if (!email.value) return showToast(t("inviteFriends.qsrndyx"));
  if (!password.value) return showToast(t("inviteFriends.qsrndmm"));
  // 名称校验,长度
  if (!name.value) return showToast(t("inviteFriends.qsrmc"));
  // 密码,正则校验
  if (!isPassword(password.value)) {
    return showToast(t("inviteFriends.passwordFormat"));
  }
  // 请选择地区
  if (!area.value) return showToast(t("inviteFriends.qxzdq"));

  // 统一遮罩
  showLoadingToast({
    message: `${t("common.requestIng")}...`,
    forbidClick: true,
    duration: 15000,
    zIndex: 999999999,
  });
  // 注册完成的回调,无论成功失败都跳转
  const call = (val: any) => {
    // https://reg.forexdana.trade/fx/forexDana/download
    if (window) {
      if (isiOS.value) {
        window.location.href = "https://apps.apple.com/app/id1641836061"; // btcDana
      } else {
        if (globalStore.packagePrefix.includes("ForexDanaTrade")) {
          window.location.href =
            "https://reg-trade.forexdana.trade/fx/forexDanaTrade/download";
        }
        // 绿包已下架,跳转到下面的链接,最终下载还是 BtcDanaTrading 包
        else if (globalStore.packagePrefix.includes("BtcDanaAsia")) {
          window.location.href =
            "https://reg-invest.btcdana.org/fx/btcDanaInvest/download";
        }
        // 还没有上线
        else if (globalStore.packagePrefix.includes("BtcDanaElite")) {
          window.location.href =
            "https://reg.forexdana.trade/fx/BtcDanaElite/download";
        } else if (globalStore.packagePrefix.includes("BtcDanaTrading")) {
          window.location.href =
            "https://reg-trading.btcdana.org/fx/btcDanaTrading/download";
        } else if (globalStore.packagePrefix.includes("ForexDana")) {
          window.location.href =
            "https://reg.forexdana.trade/fx/forexDana/download";
        }
        // 默认 BtcDana
        else {
          window.location.href = "https://reg.btcdana.org/fx/btcDana/download";
        }
      }
    }
  };

  // 第三方注册接口
  if (route.query.isThreeParties) {
    if (!tripartiteState.$state.isUnregistered) {
      validateTripartiteLoginApi(call);
    } else {
      if (tripartiteState.$state.type == 3) {
        showToast(`Google ${t("inviteFriends.zhyzc")}`);
      } else if (tripartiteState.$state.type == 4) {
        showToast(`FaceBook ${t("inviteFriends.zhyzc")}`);
      }
    }
  }
  // 用户手动输入的邮箱,调用这个接口注册
  else {
    newMailboxRegisterApi(call);
  }
};

/**
 * @description: 返回上一级
 */
const file = getOssFileUrl({
  sharePage: "/invite-friends/share",
});
const handleBack = () => {
  if (route.query.hrefUrl) {
    window.location.href = route.query.hrefUrl;
  } else if (route.query.packageId) {
    window.location.href =
      file.sharePage +
      "?hiddenBar=1" +
      `&language=${route.query.language}` +
      `&packageId=${route.query.packageId}` +
      `&code=${route.query.inviteCode}`;
  } else {
    navigateBack(-1);
  }
};
</script>
<style lang="scss" scoped>
.shareRegister {
  position: relative;
  background-color: #e9edf7;
  height: 100vh;
  overflow: hidden;
  padding-bottom: var(--safe-area-inset-bottom);
  &-bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 255 * 2px;
    background: linear-gradient(180deg, #8dc6ff 0%, #e8edf7 100%);
  }
}

.content {
  position: relative;
  z-index: 9;
  margin: 30 * 2px 15 * 2px 10 * 2px 15 * 2px;

  &-title {
    display: flex;
    align-items: flex-start;
    justify-content: center;
    background: linear-gradient(90deg, #85c3ff 0%, #4dc4ff 100%);
    height: 69 * 2px;
    border-radius: 12 * 2px 12 * 2px 0 0;
    overflow: hidden;
    padding-top: 12 * 2px;
    &-leftimg {
      height: 9 * 2px;
      margin-right: 10 * 2px;
      margin-top: 4.5 * 2px;
    }
    &-rightimg {
      height: 9 * 2px;
      margin-left: 10 * 2px;
      margin-top: 4.5 * 2px;
    }
    &-text {
      color: #fff;
      font-size: 17 * 2px;
      font-weight: 590;
    }
  }

  &-info {
    position: relative;
    top: -26 * 2px;
    border-radius: 12 * 2px;
    overflow: hidden;
    padding: 20 * 2px 10 * 2px;
    background-color: #fff;
  }

  &-registerInput {
    border-radius: 4 * 2px;
    background: #f0f5fa;
    padding: 12 * 2px 15 * 2px;
    margin-bottom: 20 * 2px;
    color: red;
  }
  &-select {
    padding: 12 * 2px 15 * 2px;
    justify-content: space-between;
    border-radius: 4 * 2px;
    background: #f0f5fa;
    margin-bottom: 20 * 2px;
    &-left {
      color: #999da7;
      font-size: 15 * 2px;
    }
    &-right {
      margin-left: 8 * 2px;
      height: 10 * 2px;
    }
    &-code {
      margin-left: 8 * 2px;
      color: #17191a;
      font-size: 15 * 2px;
    }
    &-icon {
      width: 28 * 2px !important;
      height: 18 * 2px !important;
    }
    &-btn {
      margin-left: 12 * 2px;
      height: 10 * 2px;
    }
  }
  &-btn {
    background: linear-gradient(90deg, #007bff 0.07%, #00b2ff 99.93%);
    box-shadow: 0px -4px 4px 0px rgba(0, 0, 0, 0.25) inset;
    text-align: center;
    width: 100%;
    padding: 14 * 2px 0;
    color: #fff;
    font-size: 17 * 2px;
    font-weight: 590;
    border-radius: 100px;
    margin-top: -8 * 2px;
  }
}
</style>
<style lang="scss">
.content-registerInput {
  .van-cell__value {
    .van-field__control {
      color: #141924;
      font-size: 15 * 2px;
      font-weight: 400;
    }
  }
  &-label {
    color: #999da7;
    font-size: 15 * 2px;
    font-weight: 400;
    min-width: 100 * 2px;
    text-wrap: nowrap;
    white-space: nowrap;
  }
}
</style>
